/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.apps.services.factory.GoogleLocationServiceFactory;
import com.apps.services.factory.UBCClassroomServiceFactory;
import com.apps.ubc.cc.model.BuildingModel;
import com.apps.utils.BookSearchUtils;

public class UBCWayfindingService {
	
		private GoogleLocationService gls = GoogleLocationServiceFactory.getGoogleLocationService();
		private UBCClassroomService crs = UBCClassroomServiceFactory.getUBCClassroomService();
	
		public UBCWayfindingService(){		
		}

		public BuildingModel search(String in) {
			BuildingModel result = null;
			try {
				result = parseURLContent(getURLContentReader(in, "bldgName"));
				if(result == null){
					result = parseURLContent(getURLContentReader(in, "keyword"));
				}
				if(result == null) {
					String crsResult = crs.search(in);
					if(crsResult != null) {
						String[] latlong = gls.getLatLong(crsResult + ", Vancouver");
						return new BuildingModel(in, crsResult, "",latlong[0], latlong[1]);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result; 
		}

		private BufferedReader getURLContentReader(String search, String field)
				throws Exception {
			
			String query = URLEncoder.encode(search,"UTF-8");
			String 	url = "http://www.maps.ubc.ca/PROD/search_results.php?searchTerm="+query+"&Submit=Search&searchField="+field;
			return new BufferedReader(new InputStreamReader(
					new URL(url).openStream()));
		}

		private BuildingModel parseURLContent(BufferedReader br) throws IOException {
			BuildingModel bm = null;
			String name = "";
			String address = "";
			String pcode = "";
			String line = br.readLine();
			while (line != null) {
				if(line.contains("<td style=\"background:")) {
					name = line.substring(line.indexOf("<p>")+3,line.indexOf("</p>"));
					line = br.readLine();
					if(line!=null&&line.contains("<td style=\"background:")) {
						address = line.substring(line.indexOf("<p>")+3,line.indexOf("<br>"));
						pcode = line.substring(line.indexOf("<br>")+4,line.indexOf("</p>"));
						String[] latlong = gls.getLatLong(name + " " + pcode);
						bm = new BuildingModel(name, address, pcode, latlong[0], latlong[1]);
						break;
					}
				}
				
				line = br.readLine();
			}
			return bm; 
		}
	

}
